﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XpathTool.Model;

namespace XpathTool.Helper
{
    public class XPathHelper
    {
        private static readonly XPathHelper instance = new XPathHelper();
        public static XPathHelper Instance => instance;

        private XPathHelper()
        {
            _hd = new HtmlDocument();
        }

        HtmlDocument _hd;
        int Index;
        public List<XpathObj> list;
        public List<HtmlNode> hnlist;

        //开始处理Node
        public void GetHtmlNode(string strhtml)
        {
            //htmlDcoument对象用来访问Html文档s
            HtmlDocument hd = new HtmlDocument();
            //加载Html文档
            hd.LoadHtml(strhtml);

            Index = 0;
            list = new List<XpathObj>();
            hnlist = new List<HtmlNode>();
            foreach (HtmlNode em in hd.DocumentNode.ChildNodes)
            {
                Setxpath(em);
            }
        }
        /// <summary>
        /// 递归获取Html Dom
        /// </summary>
        /// <param name="node">要处理的节点</param>
        private void Setxpath(HtmlNode node)
        {

            foreach (HtmlNode item in node.ChildNodes)
            {
                if (item.XPath.Contains("#"))
                {
                    continue;
                }
                list.Add(new XpathObj()
                {
                    id = Index.ToString(),
                    XPath = item.XPath,
                    HasAttributes = item.HasAttributes,
                    HasChildNodes = item.HasChildNodes,
                    HasClosingAttributes = item.HasClosingAttributes,
                    InnerHtml = item.InnerHtml,
                    InnerText = item.InnerText,
                    Line = item.Line,
                    LinePosition = item.LinePosition,
                    Name = item.Name,
                    OuterHtml = item.OuterHtml,
                });
                hnlist.Add(item);
                Index++;
                if (item.HasChildNodes)
                {
                    Setxpath(item);
                }
            }
        }
    }
}
